<?php
// +----------------------------------------------------------------------
// | 应用公共文件
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------


use think\facade\Db;
use think\facade\Log;
use think\facade\Config;

error_reporting(0);

function weid()
{
    global $_W;
    @session_start();
    $weid = $_W['uniacid'];
    if (isset($_SESSION['wUser']) && isset($_SESSION['wAccount'])) {
        $weid = $_SESSION['wAccount']['acid'];
    }
    if (empty($weid)) {

        if (!empty($_GET['uniacid'])) {

            $weid = $_GET['uniacid'];
        }

        if (!empty($_POST['uniacid'])) {
            $weid = $_POST['uniacid'];
        }

        if (!empty($_GET['i'])) {
            $weid = $_GET['i'];
        }

        if (!empty($_POST['i'])) {
            $weid = $_POST['i'];
        }
        if (empty($weid)) {
            $weid =  request()->param('i');
        }
    }

    return (int) $weid;
}
function gethost()
{
    $host = $_SERVER['HTTP_HOST'];
    if (empty($host)) {
        $host =    input('server.SERVER_NAME');;
    }
    return input('server.REQUEST_SCHEME') . '://' . $host;
}
function getRealIP()
{
    $forwarded = request()->header("x-forwarded-for");
    if ($forwarded) {
        $ip = explode(',', $forwarded)[0];
    } else {
        $ip = request()->ip();
    }
    return $ip;
}

function seturl($path)
{
    $tmppath = explode('/', $path);
    if ($tmppath[0] == 'https:' || $tmppath[0] == 'http:') {
    } else {
        $path = 'http://' . $path;
    }

    return $path;
}
function getpage()
{
    $limit = input('post.limit', 20, 'intval');
    $page = input('post.page', '', 'intval');
    $is_search = input('post.is_search', '', 'intval');

    if (!empty($is_search)) {
        $page = 1;
    }
    return ['list_rows' => $limit, 'page' => $page];
}
function pass_hash($passwordinput, $salt, $create_time)
{

    global $_W;

    $passwordinput = "{$passwordinput}-{$salt}-{$create_time}";

    return sha1($passwordinput);
}

if (!function_exists('iunserializer')) {

    function iunserializer($value)
    {
        if (empty($value)) {
            return array();
        }
        if (!is_serialized($value)) {
            return $value;
        }
        if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
            $result = unserialize($value, array('allowed_classes' => false));
        } else {
            if (preg_match('/[oc]:[^:]*\d+:/i', $value)) {
                return array();
            }
            $result = unserialize($value);
        }
        if ($result === false) {
            $temp = preg_replace_callback('!s:(\d+):"(.*?)";!s', function ($matchs) {
                return 's:' . strlen($matchs[2]) . ':"' . $matchs[2] . '";';
            }, $value);
            return unserialize($temp);
        } else {
            return $result;
        }
    }
}

if (!function_exists('is_serialized')) {

    function is_serialized($data, $strict = true)
    {
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if ('N;' == $data) {
            return true;
        }
        if (strlen($data) < 4) {
            return false;
        }
        if (':' !== $data[1]) {
            return false;
        }
        if ($strict) {
            $lastc = substr($data, -1);
            if (';' !== $lastc && '}' !== $lastc) {
                return false;
            }
        } else {
            $semicolon = strpos($data, ';');
            $brace = strpos($data, '}');
            if (false === $semicolon && false === $brace)
                return false;
            if (false !== $semicolon && $semicolon < 3)
                return false;
            if (false !== $brace && $brace < 4)
                return false;
        }
        $token = $data[0];
        switch ($token) {
            case 's':
                if ($strict) {
                    if ('"' !== substr($data, -2, 1)) {
                        return false;
                    }
                } elseif (false === strpos($data, '"')) {
                    return false;
                }
            case 'a':
                return (bool) preg_match("/^{$token}:[0-9]+:/s", $data);
            case 'O':
                return false;
            case 'b':
            case 'i':
            case 'd':
                $end = $strict ? '$' : '';
                return (bool) preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
        }
        return false;
    }
}

//根据键名获取键值
function getItemVal($val, $item_config)
{
    if ($val) {
        $str = '';
        foreach (explode(',', $val) as $v) {
            foreach (json_decode($item_config, true) as $m) {
                if ($v == $m['val']) {
                    $str .= $m['key'] . ',';
                }
            }
        }
        return rtrim($str, ',');
    }
}

//根据键值获取键名
function getValByKey($val, $item_config)
{
    if ($val) {
        $str = '';
        foreach (explode(',', $val) as $v) {
            foreach (json_decode($item_config, true) as $m) {
                if ($v == $m['key']) {
                    $str .= $m['val'] . ',';
                }
            }
        }
        return rtrim($str, ',');
    }
}

function time_format($time = NULL, $format = 'Y-m-d H:i')
{
    $time = intval($time);

    if (empty($time)) {
        return '无';
    } else {
        return date($format, $time);
    }
}

function time_ymd($time = NULL, $format = 'Y-m-d')
{
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}

function time_md($time = NULL, $format = 'm-d')
{
    $time = $time === NULL ? time() : intval($time);
    return date($format, $time);
}

//无限极分类转为带有 children的树形select结构
function _generateSelectTree($data, $pid = 0)
{
    $tree = [];
    if ($data && is_array($data)) {
        foreach ($data as $v) {
            if ($v['pid'] == $pid) {
                $tree[] = [
                    'key' => $v['key'],
                    'val' => $v['val'],
                    'children' => _generateSelectTree($data, $v['val']),
                ];
            }
        }
    }
    return $tree;
}

//无限极分类转为带有 children的树形list表格结构
function _generateListTree($data, $pid = 0, $config = [])
{
    $tree = [];
    if ($data && is_array($data)) {
        foreach ($data as $v) {
            if ($v[$config[1]] == $pid) {
                $tree[] = array_merge($v, ['children' => _generateListTree($data, $v[$config[0]], $config)]);
            }
        }
    }
    return $tree;
}

function deldir($dir)
{
    //先删除目录下的文件：
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }

    closedir($dh);
    //删除当前文件夹：
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

/*
 * 生成流水号
 * @param char(2) $type
 */
function doOrderSn($type)
{
    return date('YmdHis') . $type . substr(microtime(), 2, 3) .  sprintf('%02d', rand(0, 99));
}

//上传文件过滤
function upload_replace($str)
{
    $farr = ["/php|php3|php4|php5|phtml|pht|/is"];
    $str = preg_replace($farr, '', $str);
    return $str;
}

//关键词搜索过滤
function serach_in($str)
{
    $farr = ["/^select[\s]+|insert[\s]+|and[\s]+|or[\s]+|create[\s]+|update[\s]+|delete[\s]+|alter[\s]+|count[\s]+|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i"];
    $str = preg_replace($farr, '', $str);
    return trim($str);
}

//过滤xss
function remove_xss($string)
{
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
    $parm1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound');
    $parm2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
    $parm = array_merge($parm1, $parm2);
    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(&#0([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[$i][$j];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, '', $string);
    }
    return $string;
}

/**
 * 实例化数据库类
 * @param string        $name 操作的数据表名称（不含前缀）
 * @param array|string  $config 数据库配置参数
 * @param bool          $force 是否强制重新连接
 * @return \think\db\Query
 */
if (!function_exists('db')) {

    function db($name = '', $connect = '')
    {
        if (empty($connect)) {
            $connect = config('database.default');
        }
        return Db::connect($connect, false)->name($name);
    }
}
